#--*--coding=utf-8--*--
#MaterialCodeGenerator5.py



import sys
import json
import chardet
#from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QComboBox, QLineEdit, QPushButton, QHBoxLayout
from PySide6.QtWidgets import QApplication, QWidget, QVBoxLayout, QPushButton, QLabel, QComboBox, QLineEdit, QHBoxLayout, QMessageBox
from PySide6.QtCore import Qt
from PySide6.QtGui import QClipboard
class MaterialCodeGenerator(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()
        self.load_rules_from_json('rules1.json')

    def initUI(self):
        self.layout = QVBoxLayout()

        # 初始化下拉列表组
        self.dropdownGroups = []
        for i in range(3):
            self.addDropdownGroup()

        # 搜索框
        self.searchBox = QLineEdit(self)
        self.searchBox.textChanged.connect(self.filterComboBoxes)
        
        # 增加和删除按钮
        buttonLayout = QHBoxLayout()
        addButton = QPushButton("增加", self)
        removeButton = QPushButton("删除", self)
        addButton.clicked.connect(self.addDropdownGroup)
        removeButton.clicked.connect(self.removeDropdownGroup)
        buttonLayout.addWidget(addButton)
        buttonLayout.addWidget(removeButton)

        self.layout.addWidget(self.searchBox)
        self.layout.addLayout(buttonLayout)
        self.setLayout(self.layout)

    def load_rules_from_json(self, file_path):
        with open(file_path, 'rb') as f:
            raw_data = f.read()
            result = chardet.detect(raw_data)
            encoding = result['encoding']
        
        with open(file_path, 'r', encoding=encoding) as file:
            self.rules = json.load(file)

    def addDropdownGroup(self):
        group = [QComboBox(self) for _ in range(2)]
        for comboBox in group:
            comboBox.addItems(self.rules['part1'])  # 确保这里的键名与JSON文件一致
        self.dropdownGroups.append(group)
        for comboBox in group:
            self.layout.addWidget(comboBox)

    def removeDropdownGroup(self):
        if self.dropdownGroups:
            group = self.dropdownGroups.pop()
            for comboBox in group:
                comboBox.deleteLater()

    def filterComboBoxes(self, text):
        for group in self.dropdownGroups:
            for comboBox in group:
                current_text = comboBox.currentText()
                comboBox.clear()
                items = [comboBox.itemText(i) for i in range(comboBox.count())]
                filtered_items = [item for item in items if text.lower() in item.lower()]
                comboBox.addItems(filtered_items)
                comboBox.setCurrentText(current_text)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = MaterialCodeGenerator()
    ex.show()
    sys.exit(app.exec())